<template>
  <div class="container">

    <sq-header :selected="1"></sq-header>

    <div class="order-info">
      <div class="buy-order-success">
         <img src="../assets/buysuccess.png" width="28px" height="28px" />
         <h3>您已成功购买课程</h3>
      </div>
      <div v-if="courseInfo.name" class="buy-order-course-name">{{courseInfo.name}}</div>
    </div>

    <div class="bind-info">

          <h3>绑定手机号码，课程永久可听</h3>

          <div class="sq-input-group">
            <input type="number" id="sq-input-mobile" name="phone" @keypress='validatePhone($event)' v-model="phone" placeholder="请输入手机号码" maxlength="11">
          </div>
          <div class="sq-input-group">
            <input type="number" id="sq-input-code" maxlength="6" @keypress='validateCode($event)' @keyup.enter="login" name="code" v-model="code" placeholder="请输入动态密码">
            <button :disabled="leftSeconds > 0" @click="sendCode" style="outline: none">{{sendCodeButtonText}}</button>
          </div>
          <div class="sq-input-group" style="flex-direction: column;">
            <div class="errtips">{{errtips}}</div>
          </div>
          <div class="modal-footer">
            <button class="modal-default-button" @click="checkBind" style="outline: none">
              立即绑定
            </button>
          </div>
          <div class="sq-input-group" style="flex-direction: column;">
            <div class="usertips">本人已阅读并同意<a href="http://m.sstt.iflyvoice.com/user_agreement.html" target="_blank">用户协议</a></div>
          </div>
    </div>

  </div>
</template>

<script>
import Vue from 'vue'
import { Toast } from 'mint-ui';
import { bind, getCourseInfoByOrderSN } from '../api/index'
import SqHeader from '../components/Header'
Vue.component(SqHeader.name, SqHeader)

const RESEND_CODE_INTERVAL = 30;

export default {
  name: 'Bind',
  data () {
    return {
      phone: "",
      code: "",
      errtips: "",
      leftSeconds: 0,
      orderSN: "",
      courseInfo: {}
    }
  },
  created: function() {
    this.orderSN = this.$route.params.orderSN;
    this.countDown();
    this.getCourseInfo();
  },
  methods: {
    getCourseInfo() {
      var that = this;
      getCourseInfoByOrderSN(this.orderSN).then(function(resp){
        if(resp.code == 0){
          that.courseInfo = resp.data;
          // 如果没有购买成功，跳转回到课程页面
          if(parseInt(that.courseInfo.hasBuy) === 0) {
            that.$router.replace({ name: 'Course', params: { id: that.courseInfo.id, randId: that.courseInfo.randId }});
            return;
          }
        }else{
          that.$router.replace('/error/500');
        }
      }).catch(function(err){
        console.log(err);
        that.$router.replace('/error/500');
      });
    },
    checkBind() {
      //check param
      if(!this.phone){
        this.errtips = "请输入手机号码"
        return false;
      }
      var reg = /^1[0-9]{10}$/;
      if(!reg.test(this.phone)){
        this.errtips = "请输入正确的手机号码"
        return false;
      }
      if(!this.code){
        this.errtips = "请输入验证码"
        return false;
      }
      reg = /^[0-9]{6}$/;
      if(!reg.test(this.code)){
        this.errtips = "请输入正确的验证码"
        return false;
      }
      var that = this;
      bind(this.orderSN, this.phone, this.code).then(function(resp){
        if(resp.code == 0){
          Toast({
            message: '手机号码绑定成功',
            duration: 3000
          });
          window._hmt.push(['_trackEvent', '登录', '绑定成功']);
          that.$store.dispatch('updateLastLoginPhone', {
            phone: that.phone
          });
          that.$store.dispatch('loginSuccess');
          that.$router.replace({ name: 'Course', params: { id: that.courseInfo.id, randId: that.courseInfo.randId }});
        }else{
          window._hmt.push(['_trackEvent', '登录', '绑定失败', resp.msg]);
          that.errtips = resp.msg;
        }
      }).catch(function(err){
        console.log(err);
      });
    },
    _getResendLeftSeconds() {
      var lastSendCodeTime = parseInt(this.$store.getters.lastSendCodeTime);
      var now = (new Date()).getTime();
      var left =  Math.floor((now - lastSendCodeTime)/1000);
      if(left < 0){
        return RESEND_CODE_INTERVAL;
      } else if (left > RESEND_CODE_INTERVAL){
        return 0;
      }else{
        return RESEND_CODE_INTERVAL - left;
      }
    },
    countDown() {
      this.leftSeconds = this._getResendLeftSeconds();
      if(this.leftSeconds > 0){
        setTimeout(this.countDown, 1000);
      }
    },
    sendCode() {
      if(!this.phone){
        this.errtips = "请输入手机号码"
        return false;
      }
      var reg = /^1[0-9]{10}$/;
      if(!reg.test(this.phone)){
        this.errtips = "请输入正确的手机号码"
        return false;
      }
      if(this.leftSeconds > 0) {
        return false;
      }else{
        this.$store.dispatch("sendCode", {phone: this.phone});
        this.countDown();
      }
    },
    validatePhone(event) {
      console.log("phone:" + this.phone);
      if(event.keyCode == 46 || event.keyCode == 8) {
        return true;
      }
      var isNumber = event.charCode >= 48 && event.charCode <= 57
      var res = isNumber && this.phone.length < 11;
      if(!res) {
        event.preventDefault();
      }
      console.log(res);
      return res;
    },
    validateCode(event) {
      console.log("code:" + this.code);
      if(event.keyCode == 46 || event.keyCode == 8 || event.key == 13) {
        return true;
      }
      var isNumber = event.charCode >= 48 && event.charCode <= 57
      var res = isNumber && this.code.length < 6;
      if(!res) {
        event.preventDefault();
      }
      console.log(res);
      return res;
    }
  },
  computed: {
    sendCodeButtonText: function(){
      if(this.leftSeconds > 0) {
        return this.leftSeconds + "秒后重试";
      }else{
        return "获取动态密码";
      }
    }
  }
}
</script>

<style scoped>

  .container {
  	width: 100%;
  	height: 100%;
  	margin: 0px;
  	padding: 0px;
  }

  .order-info {
    border-bottom: 11px solid #eeeeee;
  }

  .buy-order-success {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30px;
    margin-bottom: 13px;
  }

  .buy-order-success h3 {
    margin:0;
    margin-left: 5px;
    font-size: 18px;
    color: #000000;
    font-weight: normal;
  }

  .buy-order-course-name {
    text-align: center;
    font-size: 16px;
    color: #666666;
    margin-bottom: 34px;
  }

  .bind-info h3 {
    margin:0;
    margin-top: 61px;
    font-size: 18px;
    color: #000000;
    font-weight: normal;
    margin-bottom: 20px;
  }

  .sq-input-group {
    display: flex;
    align-items: center;
    padding-left: 28px;
    padding-right: 28px;
  }

  .sq-input-group label {
    flex-basis: 70px;
    flex-shrink: 0;
  }

  .sq-input-group input {
    flex-grow: 1;
    height: 48px;
    border: 1px solid #ccc;
    padding-left: 12px;
    flex: 1;
    font-size: 14px;
  }

  #sq-input-mobile {
    margin-bottom: 12px;
  }

  #sq-input-code {
    width: 60%;
    flex-grow: 1;
    min-width: 120px;
    max-width: 180px;
  }

  .sq-input-group button {
    width: 50%;
    min-width: 100px;
    background-color: #fff;
    font-size: 14px;
    color:#3385ff;
    padding: 0px;
    border: 0px;
    outline: none;
    flex-grow: 1;
    flex-basis: 100px;
  }

  .errtips {
    margin-top: 10px;
    font-size: 14px;
    height: 24px;
    padding-left: 12px;
    color: #ff4a3d;
    align-self: flex-start;
    margin-bottom: 6px;
  }

  .usertips {
    margin-top: 9px;
    font-size: 14px;
    height: 14px;
    color: #999999;
    align-self: flex-end;
  }

  .usertips a {
    text-decoration: none;
    color:#5ba5fc;
  }

  .modal-footer {
    height: 44px;
    display: flex;
  }

  .modal-footer button{
    height: 100%;
    border: 0px;
    flex-grow: 1;
    margin-left: 28px;
    margin-right: 28px;
    color: #fff;
    background-color: #fe6b40;
    font-size: 16px;
  }

  .modal-default-button {
    float: right;
  }



</style>
